package logic

import (
	"context"
	"fmt"
	mysqlinit "vipshop/models/mysql"
	"vipshop/models/redisinit"
	"vipshop/pkg"
	"vipshop/vipshoprpc/internal/svc"
	"vipshop/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *vipshoprpc.LoginRequest) (*vipshoprpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := redisinit.Client.Get("Captcha" + in.Phone + "Login").Result()
	if in.Captcha != result {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}

	result1, _ := redisinit.Client.Get("SendSms" + in.Phone + "Login").Result()
	if in.SendSms != result1 {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	var login mysqlinit.User

	mysqlinit.DB.Debug().Where("phone=?", in.Phone).Find(&login)

	if login.ID == 0 {
		return nil, fmt.Errorf("手机号已存在，请重新输入")
	}
	if login.Password != pkg.Md5password(in.Password) {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}
	return &vipshoprpc.LoginResponse{
		Id: int64(login.ID),
	}, nil
}
